import uuid

import pymysql
from pymysql import Error
from pymysql.cursors import DictCursor


def sync_role_to_ymt():
    # 数据库连接配置
    target_db_config = {
        'host': '10.1.213.159',
        'user': 'GTXS_user',
        'password': 'GTXS_user_JG123',
        'database': 'sysmandb',
        'charset': 'utf8mb4'
    }

    source_db_config = {
        'host': '10.99.81.155',
        'port': 8306,
        'user': 'root',
        'password': 'Lgmi6395',
        'database': 'jg_usercenter',
        'charset': 'utf8mb4'
    }

    try:
        # 连接源数据库和目标数据库
        source_conn = pymysql.connect(**source_db_config, cursorclass=DictCursor)
        target_conn = pymysql.connect(**target_db_config, cursorclass=DictCursor)
        with source_conn.cursor() as source_cursor, target_conn.cursor() as target_cursor:
            source_cursor.execute("""
                            select id,
                                   role_name,
                                   role_code,
                                   description,
                                   create_user,
                                   create_date,
                                   change_user,
                                   change_date,
                                   app_code,
                                   role_group,
                                   default_flag,
                                   old_role_id,
                                   old_role_code,
                                   tenant_id,
                                   remark,
                                   deleted_tag
                            from sys_role r where 1=1
                                              and not exists (select id from ymt_usercenter.sys_role yr where yr.id = r.id)
                        """)
            source_data = source_cursor.fetchall()

            count = 0
            for row in source_data:
                row['guid'] = str(uuid.uuid4())
                insert_sql = """
                    INSERT INTO sys_role (guid, tenant_id, id, role_name, role_description, role_create_time, 
                        role_create_user, deleted_tag, create_date, create_user, change_date, change_user, app_code)
                        VALUES (%(id)s, '010', %(id)s, %(role_name)s, %(description)s, NOW(), 1, 'N', %(create_date)s, 
                        %(create_user)s, %(change_date)s, %(change_user)s, %(app_code)s)
                """

                target_cursor.execute(insert_sql, row)

                count += 1
                print(count)

            # 提交事务
            target_conn.commit()

            print(f"同步角色数据完成！总计: {count} 条记录")

    except Error as e:
        print(f"数据库操作出错: {e}")
        # 回滚事务
        if 'target_conn' in locals():
            target_conn.rollback()
    finally:
        # 关闭数据库连接
        if 'source_conn' in locals():
            source_conn.close()
        if 'target_conn' in locals():
            target_conn.close()


if __name__ == '__main__':
    sync_role_to_ymt()